﻿// lightShaders declarations
void DirectionalLight(	in int i,
						in vec3 normal,
						inout vec4 ambient,
						inout vec4 diffuse,
						inout vec4 specular);
void PointLight(	in int i,
					in vec3 eye,
					in vec3 ecPosition3,
					in vec3 normal,
					inout vec4 ambient,
					inout vec4 diffuse,
					inout vec4 specular);
void SpotLight(	in int i,
				in vec3 eye,
				in vec3 ecPosition3,
				in vec3 normal,
				inout vec4 ambient,
				inout vec4 diffuse,
				inout vec4 specular);

//  textureShader declarations
void applyTexture2D(in sampler2D texUnit, in int type, inout vec4 color);

// interpolated from vertex shader
varying vec3 position, ecPosition3, normal;
varying vec4 ecPosition4;

// texture
uniform sampler2D myTexture;

// cut parameters
uniform vec3 origin;
uniform vec3 uVertex;
uniform vec3 vVertex;
uniform vec3 wVertex;

uniform float uMin, uMax, vMin, vMax, wMin, wMax;

void main()
{
	vec3 local = position - origin;
	vec3 uAxis = uVertex - origin;
	vec3 vAxis = vVertex - origin;
	vec3 wAxis = wVertex - origin;

	/* cutting here */
	float u = dot(local, uAxis) / ( length(uAxis)*length(uAxis) );
	float v = dot(local, vAxis) / ( length(vAxis)*length(vAxis) );
	float w = dot(local, wAxis) / ( length(wAxis)*length(wAxis) );
	
	if(u >= uMin && u <= uMax)
		if(v >= vMin && v <= vMax)
			if(w >= wMin && w <= wMax)
				discard;

	/* end of cutting */

	// Clear the light intensity accumulators
	vec4 color = vec4(0.0);
	vec4 amb = vec4(0.0);
	vec4 diff = vec4(0.0);
	vec4 spec = vec4(0.0);
	vec3 eye;
	
	eye = vec3(0.0, 0.0, 1.0);
	
	// Loop through enabled lights, compute contribution from each
	for (int i = 0; i < 1; i++)
	{
		if (gl_LightSource[i].position.w == 0.0)
			DirectionalLight(i, normal, amb, diff, spec);
		else if (gl_LightSource[i].spotCutoff == 180.0)
			PointLight(i, eye, ecPosition3, normal, amb, diff, spec);
		else
			SpotLight(i, eye, ecPosition3, normal, amb, diff, spec);
	}
	
	color += gl_FrontLightModelProduct.sceneColor;
	color += amb * gl_FrontMaterial.ambient;
	color += diff * gl_FrontMaterial.diffuse;
	color += spec * gl_FrontMaterial.specular;
	
	vec3 texColor = vec3(texture2D(myTexture, gl_TexCoord[0].st));
	if(length(texColor) > 0.0001)
		applyTexture2D(myTexture, 1, color);
	
	gl_FragColor = color;
}